//
//  TicketPopView.m
//  markmap
//
//  Created by 甘世清 on 2024/7/19.
//

#import "TicketPopView.h"
#import "TicketCollectionViewCell.h"
#import <RMStore/RMStore.h>
#import "FiveStarPopView.h"
#import "UploadStarViewController.h"
@implementation TicketPopView

+(void)SQ_show:(UIView*)bgview{
    UserModel * model = [UserModel share];
    if (model.isTicket) {
        return;
    }
    if ([model.userid isEqualToString:@"125"]) {
        return;
    }
    NSString * valuue = [Manager SQ_stringForKey:@"userinfo_switch"];
    if ([valuue isEqualToString:@"1"]) {
        return;
    }
    
    TicketPopView  * vc = [[TicketPopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                             parentView:bgview
                                               popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
      pop.hemStyle = LSTHemStyleCenter;
    pop.isStack = YES;
      [pop pop];
    LSTPopViewWK(pop)
    [vc setTicketBlock:^(BOOL isTicket) {
        [wk_pop dismiss];
    }];
   
}
- (void)dealloc{
    [self.timer60 invalidate];
    [self.timer120 invalidate];
    self.timer60 = nil;
    self.timer120 = nil;
}
- (void)SQ_UIViewForSelfView{
    [self.collectionView registerClass:[TicketCollectionViewCell class] forCellWithReuseIdentifier:@"TicketCollectionViewCell"];
    self.backgroundColor = UIColor.blackColor;
    self.collectionView.userInteractionEnabled = NO;
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self).insets(UIEdgeInsetsMake(TopHeight-44, 0, 200, 0));
    }];
    
    UIImageView * bgImage = [[UIImageView alloc]init];
    bgImage.image = SQGetImage(@"弹框背景44");
    [self addSubview:bgImage];
    [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.mas_equalTo(FootHeight+330);
    }];
    
    UIImageView * topBgImage = [[UIImageView alloc]init];
    topBgImage.image = SQGetImage(@"38bg");
    topBgImage.layer.cornerRadius = 36;
    topBgImage.layer.masksToBounds = YES;
    [self addSubview:topBgImage];
    [topBgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.width.mas_equalTo(SCREEN_WIDETH-50);
        make.height.mas_equalTo(72);
        make.top.equalTo(bgImage).offset(130);
    }];
    
    UILabel * yongjiu = [[UILabel alloc]init];
    yongjiu.text = SQNSLocalString(@"永久");
    yongjiu.font = FONT_SEMIBOLD(14);
    yongjiu.layer.cornerRadius = 15;
    yongjiu.layer.masksToBounds = YES;
    yongjiu.backgroundColor = UIColor.blackColor;
    yongjiu.textAlignment = NSTextAlignmentCenter;
    yongjiu.textColor = SQColor(@"#FFCD48");
    [self addSubview:yongjiu];
    [yongjiu mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(64);
            make.height.mas_equalTo(30);
            make.top.equalTo(topBgImage.mas_top).offset(-15);
            make.right.equalTo(topBgImage.mas_right).offset(-16);
    }];
    UILabel * xianshi = [[UILabel alloc]init];
    xianshi.text = SQNSLocalString(@"限时优惠");
    xianshi.font = FONT_MEDIUM(14);
    xianshi.textColor = SQColor(@"#FF4E4E");
    [topBgImage addSubview:xianshi];
    [xianshi mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(topBgImage);
            make.left.equalTo(topBgImage).offset(44);
    }];
    [topBgImage addSubview:self.moneyLabel];
    [topBgImage addSubview:self.lineMoneyLabel];
    [self.moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topBgImage);
        make.left.equalTo(xianshi.mas_right).offset(10);
    }];
    [self.lineMoneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topBgImage);
        make.left.equalTo(self.moneyLabel.mas_right).offset(10);
    }];
    [self addSubview:self.fiveBtn];
    [self.fiveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.width.mas_equalTo(SCREEN_WIDETH);
        make.height.mas_equalTo(30);
        make.bottom.equalTo(self.mas_bottom).offset(-FootHeight-10);
    }];
    
    HeaderView * playBtn = [[HeaderView alloc]init];
    playBtn.text = SQNSLocalString(@"加入我们");
    playBtn.colorString = @"#BF33FF";
    playBtn.font = FONT_MEDIUM(16);
    [playBtn.btn addTarget:self action:@selector(SQ_PayMenpiao) forControlEvents:UIControlEventTouchUpInside];
    playBtn.layer.cornerRadius = 22;
    playBtn.layer.masksToBounds = YES;
    playBtn.layer.borderColor = SQColor(@"#BF33FF").CGColor;
    playBtn.layer.borderWidth = 1;
    [self addSubview:playBtn];
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.width.mas_equalTo(SCREEN_WIDETH-50);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(self.mas_bottom).offset(-FootHeight-50);
    }];
    WS(weakSelf);
    [self.fiveBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_popFiveStarView];
    }];
    NSString * good_comment_switch = [Manager SQ_stringForKey:@"good_comment_switch"];
    if ([good_comment_switch isEqualToString:@"1"]) {
        self.fiveBtn.hidden = NO;
    }else{
        self.fiveBtn.hidden = YES;
    }
    [self SQ_Height];
    
   
}

 

-(void)SQ_Height{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"ticket" forKey:@"key"];
    [HttpTool post:Url52 paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        self.jsonData = [[NSMutableDictionary alloc]initWithDictionary:httpModel.data];
        [self SQ_appleId ];
        [self SQ_Header];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
    NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
   
    [HttpTool post:Url60 paramDic:dict successBlock:^(BaseModel * _Nonnull httpModel) {
      
        NSArray * imageArray = [[NSArray alloc]initWithArray:httpModel.data];
        self.jsonArray = [[NSMutableArray alloc]initWithArray:imageArray];
        [self.collectionView reloadData];
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(SQ_60Time) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        self.timer60 = timer;
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
    
    [HttpTool post:Url6 paramDic:[[NSMutableDictionary alloc]init] successBlock:^(BaseModel * _Nonnull httpModel) {
        [MeModel SQ_setuserModel:httpModel];
        if ([UserModel share].isTicket) {
            if (self.TicketBlock) {
                self.TicketBlock(YES);
            }
        }
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        
    }];
}

-(void)SQ_appleId{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSString * value = [self.jsonData objectForKey:@"value"];
    NSDictionary * valueDic = [value mj_JSONObject];
    NSString * price = [valueDic objectForKey:@"price"];
    self.moneyLabel.text = [NSString stringWithFormat:@"￥%.2f",[price floatValue]];
    NSString * orgPrice = [valueDic objectForKey:@"orgPrice"];
    self.lineMoneyLabel.text = [NSString stringWithFormat:@"%.2f",[orgPrice floatValue]];
    self.lineMoneyLabel.deletelineStr = self.lineMoneyLabel.text;
    self.lineMoneyLabel.deletelineColor = SQColor(@"#C8C8C8");
    [self.lineMoneyLabel getLableSizeWithMaxWidth:200];
    NSString * appleId = [NSString stringWithFormat:@"%@",[valueDic objectForKey:@"appleId"]];
    [[RMStore defaultStore] requestProducts:[NSSet setWithArray:@[appleId]] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [YJProgressHUD hide];
        });
       if([products count] == 0){
           DTLog(@"--------------没有商品------------------");
           return;
       }
   } failure:^(NSError *error) {
       dispatch_async(dispatch_get_main_queue(), ^{
           [YJProgressHUD hide];
       });
   }];
}
 
-(void)SQ_Header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"100" forKey:@"num"];
    [HttpTool post:@"greet/list" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        NSArray * array = [NSArray arrayWithArray:httpModel.data];
        [self.peopleArray removeAllObjects];
        [self.peopleArray addObjectsFromArray:array];
        if (self.timer120) {
            [self.timer120 invalidate];
            self.timer120 = nil;
        }
        [self SQ_showMessage];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
    }];
}


-(void)SQ_showMessage{
    [self SQ_120Time];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(SQ_120Time) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer120 = timer;
}
-(void)SQ_120Time{
    if ( [UserModel share].isTicket ) {
        return;
    }
    if (self.peopleArray.count<=0 ) {
        [self SQ_Header];
    } else {
        NSDictionary * dic = [self.peopleArray lastObject];
        IMMessageModel * mo = [IMMessageModel new];
        mo.name = [dic objectForKey:@"name"];
        mo.portrait = [dic objectForKey:@"portrait"];
        mo.content = [dic objectForKey:@"content"];
        [IMMessageManager SQ_showMessage:mo];
        [self.peopleArray removeLastObject];
    }
}

-(void)SQ_PayMenpiao{
    //调用内购
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSString * value = [self.jsonData objectForKey:@"value"];
    NSDictionary * valueDic = [value mj_JSONObject];
    NSString * appleId = [NSString stringWithFormat:@"%@",[valueDic objectForKey:@"appleId"]];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
    }];
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            DTLog(@"%@",receiptData);
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:@"ticket/pay" paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                [UserModel share].isTicket = YES;
                [UserModel updateLocalUserModel:[UserModel share]];
                [YJProgressHUD showMsgWithoutView:@"购买成功"];
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if (self.TicketBlock) {
                        self.TicketBlock(YES);
                    }
                });
                
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
        }
}

-(void)SQ_60Time{
    CGFloat height = self.collectionView.contentOffset.y;
     [self.collectionView setContentOffset:CGPointMake(0,height+20) animated:YES];
    float he = (self.jsonArray.count/2 - 2)* 250;
    if (height > he) {
        [self.collectionView setContentOffset:CGPointMake(0,180) animated:NO];
    }
}
-(void)SQ_popFiveStarView{
    FiveStarPopView * vc = [[FiveStarPopView alloc]initWithFrame:CGRectMake(0, 0, 270, 250)];
    LSTPopView * pop = [LSTPopView initWithCustomView:vc
                                             parentView:nil
                                               popStyle:LSTPopStyleFade dismissStyle:LSTDismissStyleFade];
    pop.hemStyle = LSTHemStyleCenter;
    pop.isStack = YES;
    [pop pop];
    LSTPopViewWK(pop)
    [pop setBgClickBlock:^{
        [wk_pop dismiss];
    }];
   
    [vc.goUploadBtn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [wk_pop dismiss];
        UploadStarViewController * vct = [[UploadStarViewController alloc]init];
        [[Manager SQ_getCurrentViewController].navigationController pushViewController:vct animated:YES];
    }];
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.jsonArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    TicketCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TicketCollectionViewCell" forIndexPath:indexPath];
    NSDictionary * dic = [self.jsonArray objectAtIndex:indexPath.item];
    NSString * header = [NSString stringWithFormat:@"%@",[dic objectForKey:@"img"]];
    [cell.bgImage sd_setImageWithURL:SQURLImage(header) placeholderImage:SQGetImage(@"zanwutouxiang")];
    cell.juliLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"distance"]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(SCREEN_WIDETH/2.f - 20, 240);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(TopHeight, 14, 0, 14);
}

 

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.userInteractionEnabled = YES;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}
- (NSMutableArray *)peopleArray{
    if (!_peopleArray) {
        _peopleArray = [[NSMutableArray alloc]init];
    }
    return _peopleArray;
}
 
- (SQCustomButton *)fiveBtn{
    if (!_fiveBtn) {
        _fiveBtn = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(0, 0) midmargin:0];
        _fiveBtn.text = SQNSLocalString(@"五星好评免费试用");
        _fiveBtn.textColor = SQColor333333;
        _fiveBtn.font = FONT_MEDIUM(14);
    }
    return _fiveBtn;
}

- (UILabel *)moneyLabel{
    if (!_moneyLabel) {
        _moneyLabel = [[UILabel alloc]init];
        _moneyLabel.font = FONT_SEMIBOLD(28);
        _moneyLabel.textColor =  SQColor(@"#000000");
    }
    return _moneyLabel;
}
- (UILabel *)lineMoneyLabel{
    if (!_lineMoneyLabel) {
        _lineMoneyLabel = [[UILabel alloc]init];
        _lineMoneyLabel.font = FONT_MEDIUM(15);
        _lineMoneyLabel.textColor =  SQColor(@"#C8C8C8");
    }
    return _lineMoneyLabel;
}
 

@end
